/**
 * 智能文档管理状态管理
 */

import { createContext, useContext, useState, useCallback, useMemo, type ReactNode } from 'react';
import type {
  DocumentCategory,
  PersonalDocument,
  DocumentComplianceRelation,
  DocumentListResponse,
  ViewMode,
  SortField,
  SortOrder
} from '@/types/document';
import * as documentApi from '@/api/document';

// Context类型定义
interface DocumentContextType {
  // 状态数据
  categories: DocumentCategory[];
  selectedCategoryId: string | null;
  documents: PersonalDocument[];
  selectedDocumentId: string | null;
  selectedDocument: PersonalDocument | null;
  documentRelations: DocumentComplianceRelation[];
  loading: {
    categories: boolean;
    documents: boolean;
    document: boolean;
    relations: boolean;
    uploading: boolean;
  };
  pagination: {
    total: number;
    page: number;
    size: number;
    total_pages: number;
    offset: number;
    limit: number;
  };
  filter: {
    search: string;
    tagNames: string[];
    isFavorite: boolean | null;
    isPinned: boolean | null;
  };
  sort: {
    sortBy: SortField;
    sortOrder: SortOrder;
  };
  view: {
    mode: ViewMode;
    leftPanelWidth: number;
    rightPanelWidth: number;
    leftPanelCollapsed: boolean;
    rightPanelCollapsed: boolean;
  };
  selection: {
    selectedIds: string[];
    selectAll: boolean;
  };
  
  // 前端筛选状态
  showAllDocuments: boolean;
  showFavorites: boolean;
  
  // 分类操作
  fetchCategories: () => Promise<void>;
  selectCategory: (categoryId: string | null) => void;
  addCategory: (category: Omit<DocumentCategory, 'id'>) => Promise<DocumentCategory | null>;
  updateCategory: (id: string, updates: Partial<DocumentCategory>) => Promise<DocumentCategory | null>;
  deleteCategory: (id: string, targetCategoryId?: string) => Promise<boolean>;
  
  // 文档操作
  fetchDocuments: (params?: any) => Promise<void>;
  selectDocument: (documentId: string | null) => void;
  fetchDocumentDetail: (id: string) => Promise<PersonalDocument | null>;
  uploadDocument: (formData: FormData) => Promise<PersonalDocument | null>;
  updateDocument: (id: string, updates: { title?: string; description?: string; category_id?: string | null; tags?: string[]; }) => Promise<PersonalDocument | null>;
  deleteDocument: (id: string) => Promise<boolean>;
  deleteDocuments: (ids: string[]) => Promise<boolean>;
  batchMoveDocuments: (documentIds: string[], categoryId: string | null) => Promise<{ moved_count: number; message: string }>;
  toggleFavorite: (id: string) => Promise<void>;
  togglePin: (id: string) => Promise<void>;
  
  // 关联关系操作
  fetchDocumentRelations: (documentId: string) => Promise<void>;
  addDocumentRelation: (relation: Omit<DocumentComplianceRelation, 'id'>) => Promise<DocumentComplianceRelation | null>;
  deleteDocumentRelation: (id: string) => Promise<boolean>;
  
  // 筛选和排序
  updateFilter: (filter: Partial<DocumentContextType['filter']>) => void;
  updateSort: (sort: Partial<DocumentContextType['sort']>) => void;
  updatePagination: (pagination: Partial<DocumentContextType['pagination']>) => void;
  
  // 视图设置
  updateView: (view: Partial<DocumentContextType['view']>) => void;
  
  // 前端筛选操作
  updateShowAllDocuments: (show: boolean) => void;
  updateShowFavorites: (show: boolean) => void;
  
  // 选择操作
  selectDocuments: (ids: string[]) => void;
  toggleSelectAll: (selectAll: boolean) => void;
  clearSelection: () => void;
  
  // 错误状态
  error: Error | null;
}

// Context创建
const DocumentContext = createContext<DocumentContextType | undefined>(undefined);

// Provider组件
interface DocumentProviderProps {
  children: ReactNode;
}

export function DocumentProvider({ children }: DocumentProviderProps) {
  // 状态管理
  const [categories, setCategories] = useState<DocumentCategory[]>([]);
  const [selectedCategoryId, setSelectedCategoryId] = useState<string | null>(null);
  const [documents, setDocuments] = useState<PersonalDocument[]>([]);
  const [selectedDocumentId, setSelectedDocumentId] = useState<string | null>(null);
  const [selectedDocument, setSelectedDocument] = useState<PersonalDocument | null>(null);
  const [documentRelations, setDocumentRelations] = useState<DocumentComplianceRelation[]>([]);
  const [error, setError] = useState<Error | null>(null);
  
  const [loading, setLoading] = useState({
    categories: false,
    documents: false,
    document: false,
    relations: false,
    uploading: false,
  });
  
  const [pagination, setPagination] = useState({
    total: 0,
    page: 1,
    size: 20,
    total_pages: 0,
    offset: 0,
    limit: 20,
  });
  
  const [filter, setFilter] = useState({
    search: '',
    tagNames: [] as string[],
    isFavorite: null as boolean | null,
    isPinned: null as boolean | null,
  });
  
  const [sort, setSort] = useState({
    sortBy: 'created_at' as SortField,
    sortOrder: 'desc' as SortOrder,
  });
  
  const [view, setView] = useState({
    mode: 'list' as ViewMode,
    leftPanelWidth: 20,
    rightPanelWidth: 20,
    leftPanelCollapsed: false,
    rightPanelCollapsed: false,
  });
  
  const [selection, setSelection] = useState({
    selectedIds: [] as string[],
    selectAll: false,
  });
  
  // 前端筛选状态
  const [showAllDocuments, setShowAllDocuments] = useState(true);
  const [showFavorites, setShowFavorites] = useState(false);

  // 分类操作
  const fetchCategories = useCallback(async () => {
    setLoading(prev => ({ ...prev, categories: true }));
    setError(null);
    try {
      const categoriesData = await documentApi.fetchCategoryTree();
      setCategories(categoriesData);
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to fetch categories');
      setError(error);
      throw error;
    } finally {
      setLoading(prev => ({ ...prev, categories: false }));
    }
  }, []);

  const selectCategory = useCallback((categoryId: string | null) => {
    setSelectedCategoryId(categoryId);
    // 切换分类时清空选择
    setSelection({ selectedIds: [], selectAll: false });
  }, []);

  const addCategory = useCallback(async (category: Omit<DocumentCategory, 'id'>) => {
    try {
      const newCategory = await documentApi.createCategory(category);
      if (newCategory) {
        setCategories(prev => [...prev, newCategory]);
      }
      return newCategory;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to add category');
      setError(error);
      throw error;
    }
  }, []);

  const updateCategory = useCallback(async (id: string, updates: Partial<DocumentCategory>) => {
    try {
      const updatedCategory = await documentApi.updateCategory(id, updates);
      if (updatedCategory) {
        setCategories(prev => prev.map(cat => cat.id === id ? updatedCategory : cat));
      }
      return updatedCategory;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to update category');
      setError(error);
      throw error;
    }
  }, []);

  const deleteCategory = useCallback(async (id: string, targetCategoryId?: string) => {
    try {
      await documentApi.deleteCategory(id, targetCategoryId);
      // API返回 {message: string}，表示成功
      setCategories(prev => prev.filter(cat => cat.id !== id));
      if (selectedCategoryId === id) {
        setSelectedCategoryId(null);
      }
      return true;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to delete category');
      setError(error);
      throw error;
    }
  }, [selectedCategoryId]);

  // 文档操作
  const fetchDocuments = useCallback(async (params?: any) => {
    setLoading(prev => ({ ...prev, documents: true }));
    setError(null);
    try {
      const queryParams = {
        page: pagination.page,
        size: pagination.size,
        search: filter.search,
        tags: filter.tagNames,
        is_favorite: filter.isFavorite,
        is_pinned: filter.isPinned,
        category_id: selectedCategoryId,
        sort_by: sort.sortBy,
        sort_order: sort.sortOrder,
        ...params,
      };
      
      const response: DocumentListResponse = await documentApi.fetchDocuments(queryParams);
      setDocuments(response.items || []);
      setPagination(prev => ({
        ...prev,
        total: response.total,
        page: response.page,
        size: response.size,
        total_pages: response.total_pages,
        offset: (response.page - 1) * response.size,
      }));
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to fetch documents');
      setError(error);
      throw error;
    } finally {
      setLoading(prev => ({ ...prev, documents: false }));
    }
  }, [pagination.page, pagination.size, filter, selectedCategoryId, sort]);

  const selectDocument = useCallback((documentId: string | null) => {
    setSelectedDocumentId(documentId);
  }, []);

  const fetchDocumentDetail = useCallback(async (id: string) => {
    setLoading(prev => ({ ...prev, document: true }));
    setError(null);
    try {
      const document = await documentApi.fetchDocumentDetail(id);
      setSelectedDocument(document);
      return document;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to fetch document detail');
      setError(error);
      throw error;
    } finally {
      setLoading(prev => ({ ...prev, document: false }));
    }
  }, []);

  const uploadDocument = useCallback(async (formData: FormData) => {
    setLoading(prev => ({ ...prev, uploading: true }));
    setError(null);
    try {
      const newDocument = await documentApi.uploadDocument(formData);
      if (newDocument) {
        setDocuments(prev => [newDocument, ...prev]);
        setPagination(prev => ({ ...prev, total: prev.total + 1 }));
      }
      return newDocument;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to upload document');
      setError(error);
      throw error;
    } finally {
      setLoading(prev => ({ ...prev, uploading: false }));
    }
  }, []);

  const updateDocument = useCallback(async (id: string, updates: { title?: string; description?: string; category_id?: string | null; tags?: string[]; }) => {
    try {
      const updatedDocument = await documentApi.updateDocument(id, updates);
      if (updatedDocument) {
        setDocuments(prev => prev.map(doc => doc.id === id ? updatedDocument : doc));
        if (selectedDocument?.id === id) {
          setSelectedDocument(updatedDocument);
        }
      }
      return updatedDocument;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to update document');
      setError(error);
      throw error;
    }
  }, [selectedDocument]);

  // 删除单个文档
  const deleteDocument = useCallback(async (id: string) => {
    try {
      await documentApi.deleteDocument(id);
      // 从文档列表中移除
      setDocuments(prev => prev.filter(doc => doc.id !== id));
      setPagination(prev => ({ ...prev, total: prev.total - 1 }));
      // 从选择列表中移除
      setSelection(prev => ({
        selectedIds: prev.selectedIds.filter(selectedId => selectedId !== id),
        selectAll: false
      }));
      // 如果删除的是当前选中的文档，清空选择
      if (selectedDocumentId === id) {
        setSelectedDocumentId(null);
        setSelectedDocument(null);
      }
      return true;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to delete document');
      setError(error);
      throw error;
    }
  }, [selectedDocumentId]);

  const deleteDocuments = useCallback(async (ids: string[]) => {
    try {
      const result = await documentApi.batchDeleteDocuments(ids);
      // API返回 {deleted_count: number; message: string}
      setDocuments(prev => prev.filter(doc => !ids.includes(doc.id)));
      setPagination(prev => ({ ...prev, total: prev.total - result.deleted_count }));
      // 清空选择
      setSelection({ selectedIds: [], selectAll: false });
      // 如果删除的是当前选中的文档，清空选择
      if (selectedDocumentId && ids.includes(selectedDocumentId)) {
        setSelectedDocumentId(null);
        setSelectedDocument(null);
      }
      return true;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to delete documents');
      setError(error);
      throw error;
    }
  }, [selectedDocumentId]);

  const toggleFavorite = useCallback(async (id: string) => {
    try {
      await documentApi.toggleFavorite(id);
      // 更新文档列表中的收藏状态
      setDocuments(prev => prev.map(doc => 
        doc.id === id ? { ...doc, is_favorite: !doc.is_favorite } : doc
      ));
      // 更新选中文档的收藏状态
      if (selectedDocument?.id === id) {
        setSelectedDocument(prev => prev ? { ...prev, is_favorite: !prev.is_favorite } : prev);
      }
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to toggle favorite');
      setError(error);
      throw error;
    }
  }, [selectedDocument]);

  const togglePin = useCallback(async (id: string) => {
    try {
      await documentApi.togglePin(id);
      // 更新文档列表中的置顶状态
      setDocuments(prev => prev.map(doc => 
        doc.id === id ? { ...doc, is_pinned: !doc.is_pinned } : doc
      ));
      // 更新选中文档的置顶状态
      if (selectedDocument?.id === id) {
        setSelectedDocument(prev => prev ? { ...prev, is_pinned: !prev.is_pinned } : prev);
      }
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to toggle pin');
      setError(error);
      throw error;
    }
  }, [selectedDocument]);

  // 关联关系操作
  const fetchDocumentRelations = useCallback(async (documentId: string) => {
    setLoading(prev => ({ ...prev, relations: true }));
    setError(null);
    try {
      const relations = await documentApi.fetchDocumentRelations(documentId);
      setDocumentRelations(relations);
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to fetch document relations');
      setError(error);
      throw error;
    } finally {
      setLoading(prev => ({ ...prev, relations: false }));
    }
  }, []);

  const addDocumentRelation = useCallback(async (relation: Omit<DocumentComplianceRelation, 'id'>) => {
    try {
      const newRelation = await documentApi.createDocumentRelation(relation);
      if (newRelation) {
        setDocumentRelations(prev => [...prev, newRelation]);
      }
      return newRelation;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to add document relation');
      setError(error);
      throw error;
    }
  }, []);

  const deleteDocumentRelation = useCallback(async (id: string) => {
    try {
      await documentApi.deleteDocumentRelation(id);
      // API返回 {message: string}，表示成功
      setDocumentRelations(prev => prev.filter(rel => rel.id !== id));
      return true;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to delete document relation');
      setError(error);
      throw error;
    }
  }, []);

  // 筛选和排序
  const updateFilter = useCallback((newFilter: Partial<DocumentContextType['filter']>) => {
    setFilter(prev => ({ ...prev, ...newFilter }));
    // 更新筛选条件时重置分页
    setPagination(prev => ({ ...prev, page: 1, offset: 0 }));
  }, []);

  const updateSort = useCallback((newSort: Partial<DocumentContextType['sort']>) => {
    setSort(prev => ({ ...prev, ...newSort }));
    // 更新排序时重置分页
    setPagination(prev => ({ ...prev, page: 1, offset: 0 }));
  }, []);

  const updatePagination = useCallback((newPagination: Partial<DocumentContextType['pagination']>) => {
    setPagination(prev => ({ ...prev, ...newPagination }));
  }, []);

  // 视图设置
  const updateView = useCallback((newView: Partial<DocumentContextType['view']>) => {
    setView(prev => ({ ...prev, ...newView }));
  }, []);

  // 前端筛选操作
  const updateShowAllDocuments = useCallback((show: boolean) => {
    setShowAllDocuments(show);
    if (show) {
      setShowFavorites(false);
    }
  }, []);

  const updateShowFavorites = useCallback((show: boolean) => {
    setShowFavorites(show);
    if (show) {
      setShowAllDocuments(false);
    }
  }, []);

  // 选择操作
  const selectDocuments = useCallback((ids: string[]) => {
    setSelection(prev => ({ ...prev, selectedIds: ids }));
  }, []);

  const toggleSelectAll = useCallback((selectAll: boolean) => {
    setSelection({
      selectAll,
      selectedIds: selectAll ? documents.map(doc => doc.id) : [],
    });
  }, [documents]);

  const clearSelection = useCallback(() => {
    setSelection({ selectedIds: [], selectAll: false });
  }, []);

  // 批量移动文档
  const batchMoveDocuments = useCallback(async (documentIds: string[], categoryId: string | null) => {
    try {
      setLoading(prev => ({ ...prev, documents: true }));
      const result = await documentApi.batchMoveDocuments(documentIds, categoryId);
      // 移动成功后清空选择并刷新文档列表
      clearSelection();
      await fetchDocuments();
      return result;
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to move documents');
      setError(error);
      throw error;
    } finally {
      setLoading(prev => ({ ...prev, documents: false }));
    }
  }, [clearSelection, fetchDocuments]);

  // 使用useMemo优化contextValue，避免不必要的重渲染
  const contextValue: DocumentContextType = useMemo(() => ({
    // 状态数据
    categories,
    selectedCategoryId,
    documents,
    selectedDocumentId,
    selectedDocument,
    documentRelations,
    loading,
    pagination,
    filter,
    sort,
    view,
    selection,
    
    // 前端筛选状态
    showAllDocuments,
    showFavorites,
    
    // 分类操作
    fetchCategories,
    selectCategory,
    addCategory,
    updateCategory,
    deleteCategory,
    
    // 文档操作
    fetchDocuments,
    selectDocument,
    fetchDocumentDetail,
    uploadDocument,
    updateDocument,
    deleteDocument,
    deleteDocuments,
    toggleFavorite,
    togglePin,
    
    // 关联关系操作
    fetchDocumentRelations,
    addDocumentRelation,
    deleteDocumentRelation,
    
    // 筛选和排序
    updateFilter,
    updateSort,
    updatePagination,
    
    // 视图设置
    updateView,
    
    // 前端筛选操作
    updateShowAllDocuments,
    updateShowFavorites,
    
    // 选择操作
    selectDocuments,
    toggleSelectAll,
    clearSelection,
    batchMoveDocuments,
    
    // 错误状态
    error,
  }), [
    categories,
    selectedCategoryId,
    documents,
    selectedDocumentId,
    selectedDocument,
    documentRelations,
    loading,
    pagination,
    filter,
    sort,
    view,
    selection,
    showAllDocuments,
    showFavorites,
    error,
    // 函数依赖
    fetchCategories,
    selectCategory,
    addCategory,
    updateCategory,
    deleteCategory,
    fetchDocuments,
    selectDocument,
    fetchDocumentDetail,
    uploadDocument,
    updateDocument,
    deleteDocument,
    deleteDocuments,
    toggleFavorite,
    togglePin,
    fetchDocumentRelations,
    addDocumentRelation,
    deleteDocumentRelation,
    updateFilter,
    updateSort,
    updatePagination,
    updateView,
    updateShowAllDocuments,
    updateShowFavorites,
    selectDocuments,
    toggleSelectAll,
    clearSelection,
  ]);

  return (
    <DocumentContext.Provider value={contextValue}>
      {children}
    </DocumentContext.Provider>
  );
}

// Hook
export function useDocument() {
  const context = useContext(DocumentContext);
  if (!context) {
    throw new Error('useDocument must be used within a DocumentProvider');
  }
  return context;
}
